import * as React from 'react';
import { SearchBox, Modal, DefaultButton, PrimaryButton, IconButton, Button } from 'office-ui-fabric-react';
import { Pivot, PivotItem, PivotLinkFormat } from 'office-ui-fabric-react/lib/Pivot';
import { ParagraphCard, ListContainer, AdvanceSearch } from '../../components';
import { documentSearch, advanceDocumentSearch, documentGet } from '../../services/documentAssistant';
import { insertHtmlAfterParagraph } from '../../utils/WordUtil';
import history from '../../utils/history';
import ParagraphsSelect from '../DocumentAssistDialog/ParagraphsSelect';

import './styles.less';
import { openDialog } from '../../utils/WordDialog';


const sortOptions = [
  {
    key: 'new',
    text: '最相关',
  },
  {
    key: 'publish_time',
    text: '最新发布',
  }
]

export interface AppProps {

}

export interface AppState {
  keyword?: string,
  showList?: boolean,
  searchType?: 'advance' | 'normal',
  type: '1' | '2' | '3',
  advanceOptions: any,
  initOptions?: any,
  queryCondition?: any,
  listItems: any,
  page: number,
  pageSize: number,
  count: number,
  showModal?: boolean
  selectId?: string
  selectDatas?: any[]
  paragraphs?: any[] // 获取到的所有上下文
  sort?: any,
  currentSort: any
}

export default class App extends React.Component<AppProps, AppState> {
  constructor(props, context) {
    super(props, context);
    this.state = {
      type: '3',
      listItems: [],
      advanceOptions: [],
      page: 1,
      pageSize: 10,
      count: 0,
      showModal: false,
      selectDatas: [],
      currentSort: sortOptions[0]
    };
  }

  componentWillMount() {
    const { type } = this.state
    this.getAdvanceOptions(type)
    // this.onSearch()
  }

  onSearch = async () => {
    const { type, keyword, page, pageSize, sort } = this.state
    const queryData = {
      kw: keyword.replace(/(^\s*)|(\s*$)/g, ""), // fix去掉空格
      type: type, // 1全文检索2章节检索3段落检索
      pageNo: page,
      pageSize,
      sort
    }

    const result = await documentSearch(queryData)
    this.setState({
      searchType: 'normal',
      showList: true,
      listItems: result.data.rsData,
      count: result.data.rsCount
    })
    console.log('result', result)
  }

  onSearchChange = (value) => {
    console.log('search', value)

    this.setState({
      keyword: value
    })
  }

  // 排序
  onSortChange = (sortItem) => {
    const { key } = sortItem
    let sort
    if (key === 'publish_time') {
      sort = {
        publish_time: { order: "desc" }
      }
    }
    // 选择后文字改变
    this.setState({
      sort,
      currentSort: sortItem
    }, this.handlePageChange) // TODO ??
  }
  // 高级搜索
  onAdvanceSearch = async (queryOptions) => {
    console.log('高级搜索search', queryOptions)
    let values = []
    let query = []
    for (let key in queryOptions) {
      if (queryOptions[key]) { // fix 删除没有的值
        query.push({
          field: key,
          vList: [queryOptions[key]]
        })
        values.push(queryOptions[key])
      }
    }

    const { type, page, pageSize, sort } = this.state
    const queryData = {
      type: type, // 1全文检索2章节检索3段落检索
      pageNo: page,
      pageSize,
      sort,
      queryCondition: JSON.stringify(query)
    }

    const result = await advanceDocumentSearch(queryData)
    console.log('高级搜索结果', result)
    this.setState({
      keyword: values.join(' '),
      showList: true,
      searchType: 'advance',
      initOptions: queryOptions,
      queryCondition: JSON.stringify(query),
      listItems: result.data.rsData,
      count: result.data.rsCount
    })
  }

  getAdvanceOptions = (tabType) => {
    let advanceOptions = []

    if (tabType !== '1') {
      advanceOptions = [
        {
          label: '标题',
          name: 'title'
        },
        {
          label: '关键词',
          name: 'kw'
        },
        {
          label: '正文',
          name: 'content'
        },
      ]
    } else {
      advanceOptions = [
        {
          label: '标题',
          name: 'title'
        },
        {
          label: '关键词',
          name: 'kw'
        },
        {
          label: '作者',
          name: 'author'
        },
        {
          label: '摘要',
          name: 'abs'
        },
        {
          label: '正文',
          name: 'content'
        },
      ]
    }

    this.setState({
      advanceOptions
    })
  }

  // 预览、插入按钮
  operateMenu = item => {
    let obj
    if (this.state.type === '1') {
      obj = {
        items: [
          {
            key: 'view',
            text: '预览',
            iconProps: {
              iconName: 'View',
            },
            onClick: () => {
              this.handleViewClick(item._id)
            }
          }
        ]
      }
    } else {
      obj = {
        items: [
          {
            key: 'view',
            text: '预览',
            iconProps: {
              iconName: 'View',
            },
            onClick: () => {
              this.handleViewClick(item._id)
            }
          },
          {
            key: 'download',
            text: '插入到word',
            iconProps: {
              iconName: 'Download',
            },
            onClick: () => {
              // fix: 移除多余的html标签 这里
              let html = '<h3>' + item.title.replace(/<[^>]+>/g, "") + '</h3>' + item.content.replace(/<[^>]+>/g, "")
              if (this.state.type === '3') {
                html = item.content.replace(/<[^>]+>/g, "")
              }
              insertHtmlAfterParagraph(html)
              return;
            }
          }
        ]
      }
    }
    return obj
  }

  render() {
    const { showList, keyword, initOptions, advanceOptions, listItems, page, count, type, selectId, showModal, currentSort } = this.state
    return (
      <div className='container document-assit'>

        <Pivot className="form-group assistant-tab"
          linkFormat={PivotLinkFormat.tabs}
          selectedKey={type}
          onLinkClick={this.handleTabChange}
          headersOnly={true}
          styles={{
            link: {
              backgroundColor: '#f4f4f4'
            },
          }}
        >
          <PivotItem linkText="片段" itemKey="3" />
          <PivotItem linkText="章节" itemKey="2" />
          <PivotItem linkText="全文" itemKey="1" />
        </Pivot>

        <AdvanceSearch
          options={advanceOptions}
          value={keyword}
          initValue={initOptions}
          onChange={this.onSearchChange}
          onSearchChange={this.onSearchChange} // 搜索下拉点击 后setstate search
          onSearch={this.onSearch}
          onAdvanceSearch={this.onAdvanceSearch}
        />

        {
          showList && (
            <ListContainer
              showContent={listItems.length > 0}
              total={count}
              current={page}
              onPageChange={this.handlePageChange} // 需要区分普通跟高级搜索
              slot={
                <DefaultButton
                  className="order"
                  data-automation-id="test"
                  // iconProps={{ iconName: 'Down' }}
                  text={currentSort.text}
                  menuProps={
                    {
                      items: sortOptions.map(
                        (item: any) => {
                          return {
                            ...item,
                            onClick: () => {
                              this.onSortChange(item)
                            }
                          }
                        }
                      )
                    }
                  }
                />
              }
            >
              <div className="search-result">
                {
                  listItems.map(
                    item => {
                      return <div onClick={() => this.handleViewClick(item._id)} key={item._id}><ParagraphCard
                        key={item._id}
                        title={item.title}
                        content={item.abs || item.content}
                        menuProps={
                          this.operateMenu(item)
                        }
                      /></div>
                    }
                  )
                }
              </div>
            </ListContainer>
          )
        }
      </div>
    );
  }

  dialog // 赋值打开的弹窗实例

  messageHandler = (arg) => {
    console.info('接收弹窗传送的段落id', arg.message)
    // const selectIds = arg.message.split(',')
    // this.getSelectHtmlAndInsert(selectIds)
    insertHtmlAfterParagraph(arg.message)
    this.dialog.close();
  }


  private handleViewClick = (id): void => {
    if (this.dialog) {
      try {
        this.dialog.close()
      } catch (err) {
      }
    }
    // 先点击打开word弹窗
    // 从word弹窗里传的是选择的段落id，通过获取上下文得到相应的 html，再调sdk插入 Word
    const { type } = this.state
    openDialog(`/documentDialog?id=${id}&type=${type}`, this.dialogCallback)

    documentGet({
      id: id,
      type: type
    }).then(
      res => {
        console.info(res)
        this.setState({
          paragraphs: res.data
        })
      }
    )

  }

  handleTabChange = (tab): void => {
    const type = tab.props.itemKey
    this.setState({
      type,
      page: 1,
      showList: false,
      listItems: []
    }, () => {
      if (this.state.keyword) {
        this.onSearch()
      }
      this.getAdvanceOptions(type)
    })
  }

  handlePageChange = (page?: any) => {
    // console.log(page);
    const { searchType } = this.state

    this.setState({
      page: page || 1,
    }, () => {
      if (searchType === 'advance') {
        return this.onAdvanceSearch(this.state.initOptions)
      }
      return this.onSearch()
    });
  }

  dialogCallback = (asyncResult) => {
    if (asyncResult.status == "failed") {

      // In addition to general system errors, there are 3 specific errors for
      // displayDialogAsync that you can handle individually.
      switch (asyncResult.error.code) {
        case 12004:
          console.error("Domain is not trusted");
          break;
        case 12005:
          console.error("HTTPS is required");
          break;
        case 12007:
          console.error("A dialog is already opened.");
          break;
        default:
          console.error(asyncResult.error.message);
          break;
      }
    }
    else {
      console.info('弹窗打开成功')
      this.dialog = asyncResult.value;
      /*Messages are sent by developers programatically from the dialog using office.context.ui.messageParent(...)*/
      this.dialog.addEventHandler(Office.EventType.DialogMessageReceived, this.messageHandler);

      /*Events are sent by the platform in response to user actions or errors. For example, the dialog is closed via the 'x' button*/
      this.dialog.addEventHandler(Office.EventType.DialogEventReceived, this.eventHandler);
    }
  }

  eventHandler(arg) {
    // In addition to general system errors, there are 2 specific errors
    // and one event that you can handle individually.
    switch (arg.error) {
      case 12002:
        console.error("Cannot load URL, no such page or bad URL syntax.");
        break;
      case 12003:
        console.error("HTTPS is required.");
        break;
      case 12006:
        // The dialog was closed, typically because the user the pressed X button.
        console.error("Dialog closed by user");
        break;
      default:
        console.error("Undefined error in dialog window");
        break;
    }
  }
}
